package com.three.controller;

import com.alibaba.fastjson.JSON;
import com.three.pojo.ChatMsg;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class Chat implements WebSocketHandler {
    private static final ChatMsg CHAT_MSG = new ChatMsg();

    private static List<WebSocketSession> arr = new ArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        arr.add(session);
        System.out.println("有客户端连接了: " + session.getRemoteAddress().getAddress());
        session.sendMessage(new TextMessage(session.getId()));   // 给用户返回一个WebSocketID 作为用户的唯一标识
        CHAT_MSG.setContent("欢迎       " + session.getId() + "       加入群聊");
        session.sendMessage(new TextMessage(JSON.toJSONString(CHAT_MSG)));
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception {
        arr.forEach(s -> {
            try {
                s.sendMessage(new TextMessage(message.getPayload().toString()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理传输错误
        System.out.println("处理传输错误");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        arr.remove(session);
        System.out.println("有客户端关闭了连接: " + session.getRemoteAddress().getAddress());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
